Back to course home
0% completed
Vote For New Content
Microsoft Hard Problems
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Best Time to Buy and Sell Stock II (medium)
Problem Statement
You are given a prices array containing the integers, where price[i] refers to the stock price on ith day.
You are allowed to do as many transactions as you like (buy one and sell one stock multiple times). You cannot engage in multiple transactions simultaneously (you must sell the stock before you buy again). However, you can buy again on the same day after selling.
Find the maximum profit you can achieve from these transactions.
Examples
-
Example 1:
- Input:
[4, 9, 2, 3, 6, 8] - Expected Output:
11 - Justification: Buy on day 1 (price = 4) and sell on day 2 (price = 9), profit = 9-4 = 5. Then buy on day 3 (price = 2) and sell on day 6 (price = 8), profit = 8-2 = 6. Total profit is 5 + 6 = 11.
- Input:
-
Example 2:
- Input:
[5, 3, 6, 2, 5, 4] - Expected Output:
6 - Justification: Buy on day 2 (price = 3) and sell on day 3 (price = 6), profit = 6-3 = 3. Then buy on day 4 (price = 2) and sell on day 5 (price = 5), profit = 5-2 = 3. Total profit is 3 + 3 = 6.
- Input:
-
Example 3:
- Input:
[10, 8, 6, 5, 4, 2] - Expected Output:
0 - Justification: Prices are decreasing each day, so there's no opportunity to make a profit. It is best not to make any transactions.
- Input:
Try it yourself
Try solving this question here:
Java
Saved to Cloud
. . . .
Solution: Multiply Strings
Solution: Best Time to Buy and Sell Stock II
Mark as Completed
On this page
Problem Statement
Examples
Try it yourself